package net.sxnic.workflow.whimpl;

import java.io.IOException;

import net.sxnic.comm.attachment.Attachment;
import net.sxnic.comm.attachment.FileSizException;
import net.sxnic.comm.attachment.FileTypeException;
import net.sxnic.comm.attachment.util.AttachmentUtils;
import net.sxnic.workflow.context.WfContextImpl;
import net.sxnic.workflow.handler.AbstractHandler;
import net.sxnic.workflow.handler.HandlerExt;
import net.sxnic.workflow.handler.WfHandlerException;
import net.sxnic.workflow.wfentity.WfEntity;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AttachmentHandler extends AbstractHandler<WfEntity> implements HandlerExt<WfEntity> {

	private static Logger logger = LoggerFactory.getLogger(AttachmentHandler.class);

	public AttachmentHandler(WfContextImpl<WfEntity> context) {
		super(context);
	}

	@Override
	public void editExecute() throws WfHandlerException {

	}

	@Override
	public void saveExecute() throws WfHandlerException {
		// 上传附件
		if (context.getUpload() != null) {
			// 验证附件大小和类型
			String errorMsg = "";
			
			try {
				errorMsg = AttachmentUtils.checkAttachment(context.getUpload(), context.getUploadFileName(), null,
						"upload.file.size."+context.getProcessName());
			} catch (FileSizException e1) {				
				e1.printStackTrace();
			} catch (FileTypeException e1) {				
				e1.printStackTrace();
			}

			if (StringUtils.isNotBlank(errorMsg)) {
				context.setErrorMsg(errorMsg);
				return;
			}

			Attachment attachment;
			try {
				attachment = AttachmentUtils.saveAttachment(context.getUpload(), context.getUploadFileName(),
						context.getProcessName());
				context.getEntity().getAttachments().add(attachment);
			} catch (IOException e) {
				e.printStackTrace();
				throw new WfHandlerException("附件上传失败！");
			}
			logger.debug("=====upload=success===" + context.getTask());
		}
	}

	@Override
	public void viewExecute() throws WfHandlerException {
	}

	@Override
	public void submitExecute() throws WfHandlerException {
		// 上传附件
		if (context.getUpload() != null) {
			// 验证附件大小和类型
			String errorMsg = "";
			
			try {
				errorMsg = AttachmentUtils.checkAttachment(context.getUpload(), context.getUploadFileName(), null,
						"");
			} catch (FileSizException e1) {
				e1.printStackTrace();
			} catch (FileTypeException e1) {
				e1.printStackTrace();
			}

			if (StringUtils.isNotBlank(errorMsg)) {
				context.setErrorMsg(errorMsg);
				return;
			}

			Attachment attachment;
			try {
				attachment = AttachmentUtils.saveAttachment(context.getUpload(), context.getUploadFileName(),
						context.getProcessName());
				context.getEntity().getAttachments().add(attachment);
			} catch (IOException e) {
				e.printStackTrace();
				throw new WfHandlerException("附件上传失败！");
			}
			logger.debug("=====upload=success===" + context.getTask());
		}

	}

}
